<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<script type="text/javascript">

    $(function(){

        var FindRealtyController = Backbone.Router.extend({
            routes: {
                "findRealty": "findRealty",
                "findRealty/type=:type/operation=:operation/adress=:adress/priceFrom=:priceFrom/priceTo=:priceTo/page=:page": "findRealtyFromHash"
            },
            // вызов с формы
            findRealty: function() {
                var findRequest = findRealtyView.getFindRequest();
                if (findRequest) {
                    /*if (window.listRealtyController) {
                        // напрямую вызываем контроллер
                        listRealtyController.findRealty(findRequest);
                    } else {
                        // если нету контроллера, передаем данные как пост запрос, с ГЕО данными что съекономит время на запрос с гео к сервису
                        $.sendPostForm("<c:url value='/listings.html'/>", "findRequest", findRequest);
                    }*/
                    findRequest.page = 1;
                    if (!window.listRealtyController) {
                        window.location = "<c:url value='/listings.html'/>#findRealty/type=" + findRequest.type + "/operation=" + findRequest.operation + "/adress=" +
                                escape(findRequest.adress) + "/priceFrom=" + findRequest.priceFrom + "/priceTo=" + findRequest.priceTo + "/page=" + findRequest.page;
                    } else {
                        listRealtyController.findRealty(findRequest);
                    }
                } else {
                    this.navigate("", {trigger: false, replace: true});
                }
            },
            // вызов с браузера
            findRealtyFromHash: function(type, operation, adress, priceFrom, priceTo, page) {
                adress = unescape(adress);
                if (window.listRealtyController) {
                    var findRequest = {type: type, operation: operation, adress: adress, priceFrom: priceFrom, priceTo: priceTo, page: page};
                    findRealtyView.setDataOnFrom(findRequest);
                    listRealtyController.findRealty(findRequest);
                }
            }
        });

        FindRealtyModel = Backbone.Model.extend({
            defaults: {
                type:"APARTMENT",
                operation: "RENT",
                adress: "",
                googleAdress: null
            },
            toDefaults: function() {
                this.set(this.defaults, {silent: true});
                this.trigger("toDefaults");
            },
            validate: function(attrs) {
                console.log("Validation:")
                console.log(attrs);
                // Валидация адреса
                if (!(attrs.adress && attrs.adress.length > 0)) {
                    return {attr: "adress", message: "Укажите адрес!"};
                }
                if (!attrs.googleAdress || attrs.googleAdress.length == 0) {
                    return {attr: "adress", message: "Укажите адрес!"};
                }
                if (attrs.googleAdress.length > 1) {
                    return {attr: "adress", message: "Укажите правильный адрес!"};
                }

                if (!(attrs.type && attrs.type.length > 0)) {
                    return {attr: "type", message: "Выберите тип недвижимости!"};
                }

                if (!(attrs.operation && attrs.operation.length > 0)) {
                    return {attr: "operation", message: "Выберите операцию!"};
                }

            },

            getPreparedFindRequest: function() {
                var findRequest = this.preSave(this.toJSON());
                return findRequest;
            },
            preSave: function(data) {
                // выбираем для отпарки только один адрес
                data.googleAdress = data.googleAdress[0];
                return data;
            }
        });

        FindRealtyView = Backbone.View.extend({
            initialize: function(){
                var self = this;

                this.model.bind("toDefaults", this.render, this);
                this.model.bind("error", this.error, this);
                this.$el.find("[name=adress]").geoinput();

                this.$el.find("#price-range").slider({
                    range: true,
                    min: 0,
                    max: 0,
                    values: [0, 0],
                    slide: function( event, ui ) {
                        self.updatePriceInfo(ui.values[0], ui.values[1]);
                    }
                });

                this.render()
            },
            render: function(){

                this.$el.find('input:radio[name=operation][value=' + this.model.get('operation') + ']').prop('checked', true);
                this.$el.find("[name=adress]").val(this.model.get('adress'));
                this.$el.find("[name=type] option[value='" + this.model.get('type')  + "']").prop("selected", true);

                this.updateSlider();

            },
            events: {
                "change input[name=operation]": "updateSlider"
            },
            error: function(el, messageObject) {
                console.log(messageObject)
                this.$el.find("div.alert-error").html(messageObject.message).show("slow");
            },
            _getPriceStringInfo: function(priceStart, priceEnd) {
                return "Цена от <strong>$" + priceStart + "</strong> до <strong>$" + priceEnd + "</strong>";
            },
            updatePriceInfo: function(priceStart, priceEnd) {
                this.$el.find("#price_info").html(this._getPriceStringInfo(priceStart, priceEnd));
            },
            updateSlider: function() {
                var operation = this.$el.find('input:radio[name=operation]:checked').val();
                if (operation == "SALE") {
                    var priceMax = CONSTATNS.MAX_PRICE_REALTY_FOR_SALE;
                    var priceMin = CONSTATNS.MIN_PRICE_REALTY_FOR_SALE;
                } else if (operation == "RENT") {
                    var priceMax = CONSTATNS.MAX_PRICE_REALTY_FOR_RENT;
                    var priceMin = CONSTATNS.MIN_PRICE_REALTY_FOR_RENT;
                } else {
                    throw "Error type operation!";
                }

                this.$el.find("#price-range").slider("option", "max", priceMax);
                this.$el.find("#price-range").slider("option", "min", priceMin);
                this.$el.find("#price-range").slider("option", "values", [
                    priceMin, priceMax
                ]);
                this.updatePriceInfo(priceMin, priceMax);
            },
            getFindRequest: function() {
                var result = this.model.set({
                    type: this.$el.find("[name=type]").val(),
                    operation: this.$el.find('input:radio[name=operation]:checked').val(),
                    googleAdress: this.$el.find("[name=adress]").geoinput("getPlaces"),
                    adress: this.$el.find("[name=adress]").val(),
                    priceFrom:$("#price-range").slider("option", "values")[0],
                    priceTo:$("#price-range").slider("option", "values")[1]
                });
                if (result) {
                    this.$el.find("div.alert-error").hide("slow");
                    var findRequest = this.model.getPreparedFindRequest();
                    return findRequest;
                }
                return false;
            },
            setDataOnFrom: function(findRequest) {
                this.$el.find("[name=type]").val(findRequest.type);
                this.$el.find('input:radio[name=operation][value="' + findRequest.operation + '"]').click();
                if (!findRequest.googleAdress) {
                    $('[name=adress]').geoinput('setValue', findRequest.adress);
                }
                findRequest.googleAdress = this.$el.find("[name=adress]").geoinput("getPlaces")[0];
                this.$el.find("#price-range").slider("option", "values", [
                    findRequest.priceFrom, findRequest.priceTo
                ]);
            }
        });

        findRealtyController = new FindRealtyController();
        findRealtyModel = new FindRealtyModel();
        findRealtyView = new FindRealtyView({ el: "#formFindRealty", model: findRealtyModel });

        $.extend(exports, { findRealtyView: findRealtyView });

    });
</script>

<%
    String url = request.getRequestURL().toString();
    if (url.endsWith("/listings.jsp")) {
%>
    <form id="formFindRealty" class="form-inline" action="listings.html">
    <fieldset>
        <div class="row">
            <div class="span2 alert alert-error" style="display:none;width:170px;">
            </div>
            <div class="span3">
                <div class="control-group">
                    <label for="focusedInput" class="control-label">Место</label>
                    <div class="controls">
                        <input type="text" value="" placeholder="адрес" autocomplete="off" name="adress" class="input-large">
                    </div>
                </div>

                <div class="row">
                    <div class="span2 ">
                        <label for="focusedInput" class="control-label">Тип:</label>
                        <div class="controls">
                            <select class="input-medium focused" name="type">
                                <option value="ANY">Любое</option>
                                <option value="APARTMENT">Квартиры</option>
                                <option value="HOUSE">Дома</option>
                                <option value="LAND">Земля</option>
                                <option value="OFFICE">Комерческая недвижимость</option>
                                <option value="GARAGE">Гараж</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="span2">
                        <div class="controls">
                            <label class="inline">
                                <input type="radio" name="operation" value="SALE" checked/>Купить
                            </label>
                            <label class="inline">
                                <input type="radio" name="operation" value="RENT"/>Арендовать
                            </label>
                        </div>
                    </div>

                </div>
                <div class="row">
                    <div class="span3" style="margin-top:10px;">
                        <div id="price_info"></div>
                    </div>
                    <div class="span3" style="margin-top:10px;">
                        <div class="controls">
                            <div id="price-range"></div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="row">
                <div class="span2 pull-right" style="margin-top: 10px;">
                    <a class="btn btn-primary pull-right" href="#findRealty" >Поиск</a>
                </div>
            </div>

        </div>

    </fieldset>
    </form>

<% } else { %>
<form id="formFindRealty" class="form-inline" action="listings.html">
    <fieldset>
        <div class="row">
            <div class="span2 alert alert-error" style="display:none;width:170px;">
            </div>
            <div class="span4">
                <div class="control-group">
                    <label for="focusedInput" class="control-label">Место</label>
                    <div class="controls">
                        <input type="text" value="" placeholder="адрес" autocomplete="off" name="adress" class="input-xlarge">
                    </div>
                </div>

                <div class="row">
                    <div class="span2 ">
                        <label for="focusedInput" class="control-label">Тип:</label>
                        <div class="controls">
                            <select class="input-medium focused" name="type">
                                <option value="ANY">Любое</option>
                                <option value="APARTMENT">Квартиры</option>
                                <option value="HOUSE">Дома</option>
                                <option value="LAND">Земля</option>
                                <option value="OFFICE">Комерческая недвижимость</option>
                                <option value="GARAGE">Гараж</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="span3">
                        <div class="controls">
                            <label class="inline">
                                <input type="radio" name="operation" value="SALE" checked/>Купить
                            </label>
                            <label class="inline">
                                <input type="radio" name="operation" value="RENT"/>Арендовать
                            </label>
                        </div>
                    </div>

                </div>
                <div class="row">
                    <div class="span4" style="margin-top:10px;">
                        <div id="price_info"></div>
                    </div>
                    <div class="span4" style="margin-top:10px;">
                        <div class="controls">
                            <div id="price-range"></div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="row">
                <div class="span2 pull-right" style="margin-top: 10px;">
                    <a class="btn btn-primary pull-right" href="#findRealty" >Поиск</a>
                </div>
            </div>

        </div>

    </fieldset>
</form>
<% } %>
